package pl.edu.agh.nn.training;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

import pl.edu.agh.nn.conf.InvalidNetworkConfigurationException;
import pl.edu.agh.nn.data.NetData;

public class FileTrainingCaseProvider extends AbstractTrainingCaseProvider {

	private String trainingFile;
	private String testingFile;

	public FileTrainingCaseProvider() {
	}

	public FileTrainingCaseProvider(String trainingFile, String testingFile) {
		super();
		this.trainingFile = trainingFile;
		this.testingFile = testingFile;
	}

	@Override
	public void configure() throws InvalidNetworkConfigurationException {
		super.configure();
		List<NetData> trainingDatas = readDataFromFile(trainingFile);
		List<NetData> testingDatas = readDataFromFile(testingFile);
		if (testingDatas == null || testingDatas.isEmpty()) {
			for (int i = 0; i < trainingDatas.size(); i++) {
				trainingCases.add(new TrainingCase(trainingDatas.get(i).getData(), null));
			}
		} else {
			if (trainingDatas.size() != testingDatas.size()) {
				throw new InvalidNetworkConfigurationException();
			}
			for (int i = 0; i < trainingDatas.size(); i++) {
				trainingCases.add(new TrainingCase(trainingDatas.get(i).getData(), testingDatas.get(i).getData()));
			}
		}
	}

	private List<NetData> readDataFromFile(String file) {
		List<NetData> result = new ArrayList<NetData>();
		if (file == null) {
			return result;
		}
		try {
			BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
			String line = null;
			while ((line = bufferedReader.readLine()) != null) {
				String[] sValues = line.split(",");
				double data[] = new double[sValues.length];

				for (int i = 0; i < sValues.length; i++) {
					double dValue = Double.parseDouble(sValues[i].trim());
					data[i] = dValue;
				}
				result.add(new NetData(data));
			}
		} catch (Exception e) {
			System.err.println("Could not read input data");
			e.printStackTrace();
		}
		return result;
	}

	public String getTrainingFile() {
		return trainingFile;
	}

	public void setTrainingFile(String trainingFile) {
		this.trainingFile = trainingFile;
	}

	public String getTestingFile() {
		return testingFile;
	}

	public void setTestingFile(String testingFile) {
		this.testingFile = testingFile;
	}
}
